package com.sgb.kjwl.view.ui.fragment.transport;

import android.Manifest;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.PopupWindow;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.databinding.DataBindingUtil;

import com.amap.api.maps.AMap;
import com.amap.api.maps.model.BitmapDescriptor;
import com.amap.api.maps.model.BitmapDescriptorFactory;
import com.amap.api.maps.model.CameraPosition;
import com.amap.api.maps.model.LatLng;
import com.amap.api.maps.model.Marker;
import com.amap.api.services.core.LatLonPoint;
import com.amap.api.services.geocoder.GeocodeResult;
import com.amap.api.services.geocoder.GeocodeSearch;
import com.amap.api.services.geocoder.RegeocodeAddress;
import com.amap.api.services.geocoder.RegeocodeQuery;
import com.amap.api.services.geocoder.RegeocodeResult;
import com.google.android.material.tabs.TabLayout;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.swgk.core.util.LogUtil;

import com.sgb.alimaplibrary.MarkerEntity;
import com.sgb.alimaplibrary.TextureMapMarkerTools;
import com.sgb.kjwl.AppLazyFragment;
import com.sgb.kjwl.R;
import com.swgk.core.event.MessageEvent;
import com.sgb.kjwl.databinding.FragmentMapGoodsBinding;
import com.sgb.kjwl.di.transport.DaggerTransportFragComponent;
import com.sgb.kjwl.di.transport.TransportFragModule;
import com.sgb.kjwl.model.entity.CarInfo;
import com.sgb.kjwl.model.entity.transport.CarTypeAndCarLength;
import com.sgb.kjwl.model.entity.transport.GoodsHallFilterEntity;
import com.sgb.kjwl.model.entity.transport.GoodsInfoTypeEntity3;
import com.sgb.kjwl.model.entity.transport.GoodsSourceLocationEntity;
import com.sgb.kjwl.model.entity.transport.MapSourcesEntity;
import com.sgb.kjwl.model.entity.user.AddressEntity;
import com.sgb.kjwl.utils.NumberUtil;
import com.sgb.kjwl.utils.TextViewUtils;
import com.swgk.core.util.UserOperating;
import com.swgk.core.event.EventConstant;
import com.sgb.kjwl.view.event.LogisticsEvent;
import com.sgb.kjwl.view.ui.activity.self.authentication.AuthActivity3;
import com.sgb.kjwl.view.ui.activity.self.logistics.AddCarActivity;
import com.sgb.kjwl.view.ui.activity.transport.MapCarBiddingActivity;
import com.sgb.kjwl.view.ui.activity.vehicleManagement.AddDriverInfoActivity;
import com.sgb.kjwl.view.widget.GoodsMoreFilterPopWindow;
import com.sgb.kjwl.view.widget.GoodsTypePopWindow3;
import com.sgb.kjwl.view.widget.LoadTimePopWindow;
import com.sgb.kjwl.view.widget.MapGoodsPopWindow;
import com.swgk.core.dialog.RoundCornerDialog;
import com.sgb.kjwl.view.widget.SetWeightAndVolumeWindow;
import com.sgb.kjwl.view.widget.ThreeLevelAreaWindow;
import com.sgb.kjwl.viewmodel.transport.MapGoodsFramgentModel;
import com.swgk.core.base.di.AppComponent;
import com.swgk.core.dialog.BasePopWindow;
import com.swgk.core.recyclerview.entity.BaseAreaEntity;
import com.swgk.core.util.MLog;
import com.swgk.core.util.MToast;
import com.swgk.core.util.PermissionUtils;
import com.swgk.core.util.ScreenUtil;
import com.swgk.core.util.SharedPreferenceUtil;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.inject.Inject;

public class MapGoodsFragment extends AppLazyFragment implements AMap.OnCameraChangeListener {

    public boolean isSelectAllCity;
    private FragmentMapGoodsBinding binding;

    private ThreeLevelAreaWindow sendGoodsLocationPopWindow3;
    private ThreeLevelAreaWindow destinationPopWindow;
    private GoodsTypePopWindow3 goodsTypePopWindow;
    private GoodsMoreFilterPopWindow goodsMorePopWindow;
    private List<GoodsInfoTypeEntity3> goodsTypeData;
    private List<GoodsInfoTypeEntity3> carsTypeData;
    private List<GoodsInfoTypeEntity3> carsLengthData;

    private int LOCATION_TYPE = 0;//0发货地，1目的地

    // 一级联动数据
    public static List<AddressEntity<List<AddressEntity<List<AddressEntity>>>>> addressEntityList;
    public static List<AddressEntity<List<AddressEntity<List<AddressEntity>>>>> destAddressEntityList;
    // 二级联动数据
    public static List<List<AddressEntity<List<AddressEntity>>>> opt2 = new ArrayList<>();
    // 三级联动数据
    public static List<List<List<AddressEntity>>> opt3 = new ArrayList<>();

    private int position = -1;

    private MapGoodsPopWindow mapGoodsPopWindow;
    private String driver = "";
    private List<CarInfo> carInfo;
    @Inject
    MapGoodsFramgentModel goodsFramgentModel;
    private TextureMapMarkerTools mapMarkerTools;
    private SetWeightAndVolumeWindow weightAndVolumeWindow;
    private LoadTimePopWindow loadTimePopWindow;
    List<MapSourcesEntity> bundles = new ArrayList<>();
    List<MapSourcesEntity> bundlesBus = new ArrayList<>();
    List<MarkerEntity> markerEntityList = new ArrayList<>();
    public LatLng currentLatLng;
    Bundle savedInstanceState;
    private Marker markerLast;
    private int lastPosition;
    //全国中心点经纬度
    public LatLng mCenterLatLng = new LatLng(35.03349, 103.03319);
    //地图缩放比例
    private float mZoom = 11;
    //最小缩放级别（全国）
    private float mMinZoom = 3;
    private boolean isLoadType;//加载地图后是否加载货物类型
    private int ampHight;
    AMap aMap;
    private boolean isMapClick;
    private String goodsTypeNo;
    private Map<String, List<CarTypeAndCarLength>> allCarTypeAndCarLengthMap = new HashMap<>();
    //屏幕高度
    private int mScreenHeight;
    public static MapGoodsFragment newInstance() {
        MapGoodsFragment fragment = new MapGoodsFragment();
        return fragment;
    }
    public static MapGoodsFragment newInstance(boolean isShowTitle) {
        MapGoodsFragment fragment = new MapGoodsFragment();
        Bundle bundle=new Bundle();
        bundle.putBoolean("isShowTitle",isShowTitle);
        fragment.setArguments(bundle);
        return fragment;
    }
    @Override
    protected void setupFragmentComponent(AppComponent appComponent) {
        DaggerTransportFragComponent.builder().appComponent(appComponent).transportFragModule(new TransportFragModule(this)).build().inject(this);
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        binding = DataBindingUtil.inflate(inflater, R.layout.fragment_map_goods, container, false);
        binding.setOnClick(this);
        this.savedInstanceState = savedInstanceState;
        return binding.getRoot();
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }
    }

    @Override
    public void onResume() {
        super.onResume();
    }

    public void initViews() {

        if(getArguments()!=null){
            boolean isShowTitle=getArguments().getBoolean("isShowTitle",false);
            if(isShowTitle){
                binding.include.titleView.setText("可视找货");
                binding.include.ivBack.setVisibility(View.GONE);
            }
        }else{
            binding.include.topLayout.setVisibility(View.GONE);
        }
        binding.tvFindGoods.setOnClickListener(this);
        binding.tvBusiness.setOnClickListener(this);
        binding.typeMore.setOnClickListener(this);
        binding.goodsMoreLayout.setOnClickListener(this);

        //货物类型
        binding.tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                if (null != goodsTypeData && goodsTypeData.size() > 0) {
                    position = tab.getPosition();
                    goodsTypeNo=goodsTypeData.get(tab.getPosition()).getNo();
                    goodsFramgentModel.sourceType.set(goodsTypeData.get(tab.getPosition()));
                    clearFilter();
                    getData();
                }
            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {
            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {
            }
        });

        //货物类型
        goodsTypePopWindow = new GoodsTypePopWindow3(getActivity());
        goodsTypePopWindow.setBgView(binding.grayLayout);
        goodsTypePopWindow.setOnResultClick(new BasePopWindow.OnResultClick() {
            @Override
            public void result(Object type, Object key2, Object key3) {
                GoodsInfoTypeEntity3 entity = (GoodsInfoTypeEntity3) type;
                position = (int) key2;
                goodsTypeNo=entity.getNo();
                binding.tabLayout.selectTab(binding.tabLayout.getTabAt(position));
                clearFilter();
                goodsFramgentModel.sourceType.set(entity);
                // getData();
                LogUtil.v("goodsInfo", "货物类型=" + entity.getName());
            }
        });
        goodsTypePopWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                binding.typeMore.setImageResource(R.drawable.btn_down);
            }
        });

        //发货省份popWindow
        sendGoodsLocationPopWindow3 = new ThreeLevelAreaWindow(getActivity()){
            @Override
            protected void resultContent(String name, String simpleName) {
                binding.tvSend.setText(simpleName);
            }
        };
        sendGoodsLocationPopWindow3.setBgView(binding.grayLayout);
        sendGoodsLocationPopWindow3.setAreaSingle();
        sendGoodsLocationPopWindow3.setCitySingle();
        sendGoodsLocationPopWindow3.setProvinceSingle();
        sendGoodsLocationPopWindow3.setShowSimpleName(true);
        sendGoodsLocationPopWindow3.setAllSingleSelect(true);
        sendGoodsLocationPopWindow3.setOnlyShowProAndCity(true);
        sendGoodsLocationPopWindow3.setOnResultClick(new ThreeLevelAreaWindow.OnResultClickProxy() {
            @Override
            protected void result(GoodsSourceLocationEntity entity) {
                goodsFramgentModel.sendLocation.set(entity);


 /*               if (entity.getCityName().equals("全国")) {
                    isSelectAllCity = true;
                    mapMarkerTools.mapMoveCamera(mCenterLatLng,mMinZoom);
                }else {
                    isSelectAllCity = false;*/
                goodsFramgentModel.getLocationModel();
                /*}*/
                getCurrentRaduis();
                getData();
                LogUtil.v("goodsInfo", "发货物地址=" + entity.getProvinceName() + "==" + entity.getCityName() + "==" + entity.getAreaName());
            }
        });

        sendGoodsLocationPopWindow3.setOnDismissListener(() -> {
            if (!binding.tvSend.getText().toString().equals("发货地")) {
                binding.llSend.setBackgroundResource(R.drawable.shape_theme_coner);
                TextViewUtils.changeTextView(getActivity(), binding.tvSend, R.mipmap.ic_down_arrow, true);
            } else {
                binding.llSend.setBackgroundResource(R.drawable.shape_gray_coner);
                TextViewUtils.changeTextView(getActivity(), binding.tvSend, R.mipmap.ic_down_arrow_n, false);
            }
        });
        //收货省份popWindow
        destinationPopWindow = new ThreeLevelAreaWindow(getActivity()){
            @Override
            protected void resultContent(String name, String simpleName) {
                binding.tvDestination.setText(simpleName);
            }
        };
        destinationPopWindow.setBgView(binding.grayLayout);
        destinationPopWindow.setAreaSingle();
        destinationPopWindow.setCitySingle();
        destinationPopWindow.setProvinceSingle();
        destinationPopWindow.setShowSimpleName(true);
        destinationPopWindow.setAllSingleSelect(true);
        destinationPopWindow.setOnlyShowProAndCity(true);
        destinationPopWindow.setOnResultClick(new ThreeLevelAreaWindow.OnResultClickProxy() {
            @Override
            protected void result(GoodsSourceLocationEntity entity) {
                goodsFramgentModel.purposeLocation.set(entity);
                getData();
                LogUtil.v("goodsInfo", "货物目的地址=" + entity.getProvinceName() + "==" + entity.getCityName() + "==" + entity.getAreaName());
            }
        });
        destinationPopWindow.setOnDismissListener(() -> {
            if (!binding.tvDestination.getText().toString().equals("目的地")) {
                binding.llDestination.setBackgroundResource(R.drawable.shape_theme_coner);
                TextViewUtils.changeTextView(getActivity(), binding.tvDestination, R.mipmap.ic_down_arrow, true);
            } else {
                binding.llDestination.setBackgroundResource(R.drawable.shape_gray_coner);
                TextViewUtils.changeTextView(getActivity(), binding.tvDestination, R.mipmap.ic_down_arrow_n, false);
            }

        });
        //更多
        goodsMorePopWindow = new GoodsMoreFilterPopWindow(getActivity());
        goodsMorePopWindow.setBgView(binding.bgPopGrayLayout);
        goodsMorePopWindow.setOnResultCallBack(new BasePopWindow.OnResultCallBack() {
            @Override
            public void result(Object result) {
                GoodsHallFilterEntity filterEntity = (GoodsHallFilterEntity) result;
                goodsFramgentModel.filterEntity.set(filterEntity);

                getData();
            }
        });
        initWeightAndVolumeWindow();
        initLoadTimePopWindow();

    /*    //当用户未登录时，不允许访问此接口
        if (!"".equals(SharedPreferenceUtil.getInstance().getSaveStringData(SharedPreferenceUtil.LOGIN_TOKEN, ""))) {
            goodsFramgentModel.getCarInfo();
        }*/
    }

    private void clearFilter() {
        goodsFramgentModel.filterEntity.get().setCarType(null);
        goodsFramgentModel.filterEntity.get().setLengthType(null);
        goodsFramgentModel.filterEntity.get().setMaxWeight(null);
        goodsFramgentModel.filterEntity.get().setMinWeight(null);
        goodsFramgentModel.filterEntity.get().setShipmentTime("");
        goodsFramgentModel.filterEntity.get().setShipmentEndTime("");
    }

    @Override
    protected void onLazyLoad() {
        initViews();
        initMap(savedInstanceState);
    }

    private void initData() {

        goodsFramgentModel.getCarsLength();
        goodsFramgentModel.getCarsType();


        driver = SharedPreferenceUtil.getInstance().getSaveStringData(SharedPreferenceUtil.DRIVER_AUTH, "");
    }

    private void getData() {
        goodsFramgentModel.getMapList();
    }

    private void initMap(Bundle savedInstanceState) {
        mapGoodsPopWindow = new MapGoodsPopWindow(getActivity());
        mapGoodsPopWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                isMapClick = false;
                MapSourcesEntity  entity = bundles.get(lastPosition);
                if(markerLast!=null){
                    if(entity.getPattern()==0) {
                        markerLast.setIcon(BitmapDescriptorFactory.fromResource(R.mipmap.jingjiahuoyuan));
                    }else{
                        markerLast.setIcon(BitmapDescriptorFactory.fromResource(R.mipmap.jingjiahuoyuan_green_1));
                    }
                }

            }
        });

        mapMarkerTools = new TextureMapMarkerTools(getActivity(), getLifecycle(), false);
        mapMarkerTools.init(savedInstanceState, binding.mapView);
     /*   mapMarkerTools.setMarkerClick(new MapMarkerTools.MarkerClick() {
            @Override
            public void onMarkerClick(int pos, String title, Marker marker) {
                setMarkStyle(pos,marker, true);
                resetMarker(marker.getId(), marker, lastPosition);
                markerLast = marker;
                lastPosition = pos;
                isMapClick = true;
                showMarkerView(pos, title);
                //  mapMarkerTools.jumpPoint(marker);

            }

            @Override
            public void onMarkerClick(int pos, String title) {

            }

            @Override
            public void onLocationChanged(Double currentLat, Double currentLong, String address) {

            }
        });*/
        aMap = binding.mapView.getMap();
        aMap.setOnCameraChangeListener(this);//拖动监听
        aMap.setOnMarkerClickListener(new AMap.OnMarkerClickListener() {
            @Override
            public boolean onMarkerClick(Marker marker) {
                isMapClick = true;
                if (marker.getObject() != null) {
                    MapSourcesEntity goods = (MapSourcesEntity) marker.getObject();
                    for(int i=0;i<bundles.size();i++){
                        if(goods.getNo().equals(bundles.get(i).getNo())){
                            setMarkStyle(i,marker, true);
                            resetMarker(marker.getId(), marker, lastPosition);
                            markerLast = marker;
                            lastPosition = i;
                            isMapClick = true;
                            showMarkerView(i);
                        }
                    }

                }
                return false;
            }
        });
        goodsFramgentModel.getAddressModel();
        initData();
    }

    public void showLocation(LatLonPoint longLat) {
        currentLatLng = new LatLng(longLat.getLatitude(), longLat.getLongitude());
        mapMarkerTools.mapMoveCamera(currentLatLng, mZoom);

    }


    public void showMarkerView(int pos) {
        MapSourcesEntity entity;
        entity = bundles.get(pos);

        mapGoodsPopWindow.showPopwindowBottom(binding.mapView);
        mapGoodsPopWindow.setData(entity);

//        TextView textView;
//        if(true){
//            textView = new TextView(getActivity());
//            textView.setTextColor(Color.parseColor("#ffffff"));
//            textView.setTextSize(15);
//            textView.setBackgroundColor(Color.parseColor("#FF2928"));
//            textView.setText("已收到");
//            textView.setWidth(200);
//            textView.setGravity(Gravity.CENTER);
//            textView.setPadding(0,10,0,10);
//        }else{
//            textView = new TextView(getActivity());
//            textView.setTextColor(Color.parseColor("#ffffff"));
//            textView.setTextSize(15);
//            textView.setBackgroundColor(Color.parseColor("#06C764"));
//            textView.setText("同意");
//            textView.setWidth(200);
//            textView.setGravity(Gravity.CENTER);
//            textView.setPadding(0,10,0,10);
//        }
//
//        InfoWindow infoWindow = new InfoWindow(textView, marker.getPosition(), -100);
////        baiduMap.showInfoWindow(infoWindow);
//
//        textView.setOnClickListener(view -> {
//            baiduMap.hideInfoWindow();
//        });
    }

    public void showMapList(List<MapSourcesEntity> datas) {
        mapMarkerTools.mapClear();
        lastPosition=0;
        try {
            if (null != datas && datas.size() > 0) {
                bundles.clear();
                addMarker(datas, "");
            } else {
                MToast.showLongToast(getActivity(), "没有更多货源了");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void showBusMapList(List<MapSourcesEntity> datas) {
        try {
            bundlesBus.clear();
            if (null != datas && datas.size() > 0) {
                addMarker(datas, "bus");
            } else {
                MToast.showLongToast(getActivity(), "暂无数据");
            }
            mapMarkerTools.zoomToSpan(currentLatLng);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void addMarker(List<MapSourcesEntity> list, String title) {
        markerEntityList.clear();
        for (MapSourcesEntity entity : list) {
            List<String> location = entity.getLocation();
            if (null != list && list.size() > 0 && !TextUtils.isEmpty(location.get(1)) && !TextUtils.isEmpty(location.get(0))) {
                LatLng latLng = new LatLng(Double.valueOf(location.get(1)), Double.valueOf(location.get(0)));
                MarkerEntity markerEntity;

                    markerEntity = new MarkerEntity(latLng, entity.getPattern()==0?R.mipmap.jingjiahuoyuan:R.mipmap.jingjiahuoyuan_green_1, entity.getNo());
                    bundles.add(entity);

                markerEntityList.add(markerEntity);
            }
        }
        for (int i = 0; i < markerEntityList.size(); i++) {
            Marker marker = aMap.addMarker(mapMarkerTools.getMarkerOptions(markerEntityList.get(i)));
            marker.setObject(bundles.get(i));
        }
    }

    //设置maker大小图标
    private void setMarkStyle(int pos,Marker marker, boolean isBigMarkView) {
        MapSourcesEntity entity=bundles.get(pos);
        BitmapDescriptor bitmapSmall =null;
        if(entity.getPattern()==0) {
             bitmapSmall = isBigMarkView ? BitmapDescriptorFactory.fromResource(R.mipmap.dw_putonghuoyuan) : BitmapDescriptorFactory.fromResource(R.mipmap.jingjiahuoyuan);
        }else{
            bitmapSmall = isBigMarkView ? BitmapDescriptorFactory.fromResource(R.mipmap.dw_jingjiahuoyuan_green) : BitmapDescriptorFactory.fromResource(R.mipmap.jingjiahuoyuan_green_1);
        }
        marker.setIcon(bitmapSmall);
    }

    private void resetMarker(String curMarkerId, Marker markerNew, int pos) {
        MapSourcesEntity entity=bundles.get(pos);
        if (null != markerLast) {
            if (!TextUtils.equals(curMarkerId, markerLast.getId())) {
                if(entity.getPattern()==0) {
                    markerLast.setIcon(BitmapDescriptorFactory.fromResource(R.mipmap.jingjiahuoyuan));
                }else{
                    markerLast.setIcon(BitmapDescriptorFactory.fromResource(R.mipmap.jingjiahuoyuan_green_1));
                }
            }
        }

    }

    @Override
    public void onClick(View v) {
        super.onClick(v);
        switch (v.getId()) {
            case R.id.ll_send:
                LOCATION_TYPE = 0;
                if (null != addressEntityList && addressEntityList.size() > 0) {
                    showSendPopWindow();
                }
                setOptionStatus(1);
                break;
            case R.id.ll_destination:
                LOCATION_TYPE = 1;
                if (null != destAddressEntityList && destAddressEntityList.size() > 0) {
                    showDestinationPopWindow();
                }
                setOptionStatus(2);
                break;
            case R.id.type_more:
                if (null != goodsTypeData && goodsTypeData.size() > 0) {
                    binding.typeMore.setImageResource(R.mipmap.btn_expand_up_gray);
                    showGoodsTypePopWindow();
                } else {
//                    goodsFramgentModel.getGoodsTypeData();
                }
                break;
            case R.id.goods_more_layout:
                setOptionStatus(4);
                if (!isContainCarTypeAndCarLengthByGoodsNo(goodsTypeNo)) {
                    goodsFramgentModel.getCarTypeAndCarLengthList(goodsTypeNo);
                } else {
                    showMoreFilterPopWindow(allCarTypeAndCarLengthMap.get(goodsTypeNo));
                }
                break;
            case R.id.tv_find_goods:
                if ("".equals(SharedPreferenceUtil.getInstance().getSaveStringData(SharedPreferenceUtil.LOGIN_TOKEN, ""))) {
                    EventBus.getDefault().postSticky("transport_to_login");
                } else {
                    if (driver.equals("SUCCESS")) {
                        if (carInfo != null && carInfo.size() > 0) {
                            MapCarBiddingActivity.start(getActivity());
                        } else {
                            showDialogAuth("nocar");
                        }
                    } else {
                        switch (driver) {
                            case "FAIL":
                                showDialogAuth("driverFail");
                                break;
                            case "STANDBY":
                                showDialogAuth("driverStandby");
                                break;
                            default:
                                showDialogAuth("driver");
                                break;
                        }
                    }
                }
                break;
            case R.id.tv_business:
                //map显示商机标记
                if ("".equals(SharedPreferenceUtil.getInstance().getSaveStringData(SharedPreferenceUtil.LOGIN_TOKEN, ""))) {
                    EventBus.getDefault().postSticky("transport_to_login");
                } else {
                    if (driver.equals("SUCCESS")) {
                        goodsFramgentModel.getBussMapList();
                    } else {
                        switch (driver) {
                            case "FAIL":
                                showDialogAuth("driverFail");
                                break;
                            case "STANDBY":
                                showDialogAuth("driverStandby");
                                break;
                            default:
                                showDialogAuth("driver");
                                break;
                        }
                    }
                }
                break;
            case R.id.tv_by_map_load:
                cityByLoction(currentLatLng.latitude, currentLatLng.longitude);
                getCurrentRaduis();
                goodsFramgentModel.sendLocation.get().setProvinceNo("");
                goodsFramgentModel.sendLocation.get().setCityNo("");
                goodsFramgentModel.sendLocation.get().setAreaNo("");
                getData();
                break;
            case R.id.transport_weight_layout:
                weightAndVolumeWindow.showPopwindow(binding.idRootLayout,0,0);
                setOptionStatus(3);
                break;
            case R.id.load_time_layout:
                loadTimePopWindow.showPopwindow(binding.idRootLayout,0,0);
                setOptionStatus(5);
                break;
        }
    }
    private void initWeightAndVolumeWindow() {
        weightAndVolumeWindow = new SetWeightAndVolumeWindow(getActivity(), (weightMin, weightMax, volumeMin, volumeMax) -> {
            goodsFramgentModel.filterEntity.get().setMaxWeight(String.valueOf(weightMax));
            goodsFramgentModel.filterEntity.get().setMinWeight(String.valueOf(weightMin));
            goodsFramgentModel.filterEntity.get().setMaxVolume(volumeMax);
            goodsFramgentModel.filterEntity.get().setVolume(volumeMin);
            getData();
        });

        weightAndVolumeWindow.setOnDismissListener(() -> {
            if (!weightAndVolumeWindow.isUnSetWeightAndVolume()) {
                binding.transportWeightLayout.setBackgroundResource(R.drawable.shape_theme_coner);
                TextViewUtils.changeTextView(getActivity(), binding.tvWeight, R.mipmap.ic_down_arrow, true);
                binding.tvWeight.setText(weightAndVolumeWindow.getWeightAndVolumeStr());
            } else {
                binding.transportWeightLayout.setBackgroundResource(R.drawable.shape_gray_coner);
                TextViewUtils.changeTextView(getActivity(), binding.tvWeight, R.mipmap.ic_down_arrow_n, false);
            }

        });
    }
    private void initLoadTimePopWindow() {
        loadTimePopWindow = new LoadTimePopWindow(getActivity());
        loadTimePopWindow.setBgView(binding.grayLayout);
        loadTimePopWindow.setOnDismissListener(() -> binding.tvLoadTime.setSelected(false));
        loadTimePopWindow.setOnResultClick(new BasePopWindow.OnResultClick() {
            @Override
            public void result(Object key1, Object key2, Object key3) {
                GoodsInfoTypeEntity3 infoTypeEntity = (GoodsInfoTypeEntity3) key1;
                if (infoTypeEntity.getName().equals("明天以后")) {
                    goodsFramgentModel.filterEntity.get().setShipmentTime(infoTypeEntity.getNo());
                    goodsFramgentModel.filterEntity.get().setShipmentEndTime("");
                } else {
                    goodsFramgentModel.filterEntity.get().setShipmentTime("");
                    goodsFramgentModel.filterEntity.get().setShipmentEndTime(infoTypeEntity.getNo());
                }
                getData();
            }
        });
        loadTimePopWindow.setOnDismissListener(() -> {
            if (loadTimePopWindow.isSetLoadTime()) {
                binding.loadTimeLayout.setBackgroundResource(R.drawable.shape_theme_coner);
                TextViewUtils.changeTextView(getActivity(), binding.tvLoadTime, R.mipmap.ic_down_arrow, true);
                binding.tvLoadTime.setText(loadTimePopWindow.getLoadTimeStr());
            } else {
                binding.loadTimeLayout.setBackgroundResource(R.drawable.shape_gray_coner);
                TextViewUtils.changeTextView(getActivity(), binding.tvLoadTime, R.mipmap.ic_down_arrow_n, false);
            }
        });
    }
    //获取货物类型后更新数据
    public void getGoodsTypeData(List<GoodsInfoTypeEntity3> list) {
        if (null != list && list.size() > 0) {
            goodsTypeData = list;
            for (int i = 0; i < list.size(); i++) {
                binding.tabLayout.addTab(binding.tabLayout.newTab().setText(list.get(i).getName()));
            }
//            showGoodsTypePopWindow();
        } else {
            MToast.showToast(getActivity(), "数据未加载");
        }
    }

    //获取车型
    public void getCarsTypeData(List<GoodsInfoTypeEntity3> list) {
        if (null != list && list.size() > 0) {
            carsTypeData = list;
        } else {
            MToast.showToast(getActivity(), "数据未加载");
        }
    }

    //获取车长
    public void getCarsLengthData(List<GoodsInfoTypeEntity3> list) {
        if (null != list && list.size() > 0) {
            carsLengthData = list;
        } else {
            MToast.showToast(getActivity(), "数据未加载");
        }
    }

    private void showSendPopWindow() {
        sendGoodsLocationPopWindow3.showPopwindow(binding.idRootLayout,0,0);
       // sendGoodsLocationPopWindow3.setData(addressEntityList);
    }

    private void showDestinationPopWindow() {
        destinationPopWindow.showPopwindow(binding.idRootLayout,0,0);
        destinationPopWindow.setData(destAddressEntityList,true);
    }

    private void showGoodsTypePopWindow() {
        goodsTypePopWindow.showPopwindow(binding.tabLayout, 0, 0);
        goodsTypePopWindow.setData(goodsTypeData, position);
    }


    private void showMoreFilterPopWindow(List<CarTypeAndCarLength> list) {
        goodsMorePopWindow.showPopwindowRight(binding.goodsMoreLayout);
        goodsMorePopWindow.setCarTypeAndCarLength(goodsTypeNo, list);
    }

    private void setOptionStatus(int index) {
        switch (index) {
            case 1:
                TextViewUtils.changeTextView(getActivity(), binding.tvSend, R.mipmap.ic_up_arrow, true);

                break;
            case 2:
                TextViewUtils.changeTextView(getActivity(), binding.tvDestination, R.mipmap.ic_up_arrow, true);
                break;
            case 3:
                TextViewUtils.changeTextView(getActivity(), binding.tvWeight, R.mipmap.ic_up_arrow, true);
                break;
            case 4:
                binding.tvMore.setSelected(true);
                break;
            case 5:
                TextViewUtils.changeTextView(getActivity(), binding.tvLoadTime, R.mipmap.ic_up_arrow, true);
                break;
        }
    }

    public void initAddressData(List<AddressEntity<List<AddressEntity<List<AddressEntity>>>>> datas) {
        Gson mGson = new Gson();
        String addressStr = mGson.toJson(datas);
        String destAddressStr = mGson.toJson(datas);
        addressEntityList = mGson.fromJson(addressStr, new TypeToken<List<AddressEntity<List<AddressEntity<List<AddressEntity>>>>>>() {
        }.getType());
        ;
        destAddressEntityList = mGson.fromJson(addressStr, new TypeToken<List<AddressEntity<List<AddressEntity<List<AddressEntity>>>>>>() {
        }.getType());
        ;
        String proName="新疆",cityName="乌鲁木齐",areaName="不限";
        if (PermissionUtils.checkPermission(getActivity(), Manifest.permission.ACCESS_FINE_LOCATION)) {
            proName=SharedPreferenceUtil.getInstance().getSaveStringData(SharedPreferenceUtil.Province, "新疆");
        }
        if (PermissionUtils.checkPermission(getActivity(), Manifest.permission.ACCESS_FINE_LOCATION)) {
            cityName=SharedPreferenceUtil.getInstance().getSaveStringData(SharedPreferenceUtil.City, "乌鲁木齐");
        }
        sendGoodsLocationPopWindow3.setDataAndPosition(datas, proName,cityName,areaName,true,false);
        BaseAreaEntity[] entities= sendGoodsLocationPopWindow3.findCode(proName,cityName,areaName);
        binding.tvSend.setText(entities[1].getSimpleName());
        binding.llSend.setBackgroundResource(R.drawable.shape_theme_coner);
        goodsFramgentModel.sendLocation.get().setProvinceNo(entities[0].getNo());
        goodsFramgentModel.sendLocation.get().setCityNo(entities[1].getNo());
        TextViewUtils.changeTextView(getActivity(), binding.tvSend, R.mipmap.ic_down_arrow, true);
        isLoadType = true;
        if (PermissionUtils.checkPermission(getActivity(), Manifest.permission.ACCESS_FINE_LOCATION)) {
            String strLat = SharedPreferenceUtil.getInstance().getString(SharedPreferenceUtil.LATITUDE_ID, "0");
            if (!TextUtils.isEmpty(strLat)) {
                double lat = NumberUtil.convertToDouble(SharedPreferenceUtil.getInstance().getString(SharedPreferenceUtil.LATITUDE_ID, "0"));
                double log = NumberUtil.convertToDouble(SharedPreferenceUtil.getInstance().getString(SharedPreferenceUtil.LONGITUDE_ID, "0"));
                currentLatLng = new LatLng(lat, log);
                mapMarkerTools.mapMoveCamera(currentLatLng, mZoom);
            } else {
                goodsFramgentModel.sendLocation.get().setProvinceName("新疆");
                goodsFramgentModel.sendLocation.get().setCityName("乌鲁木齐");
                goodsFramgentModel.sendLocation.get().setAreaName("天山区");
                goodsFramgentModel.getLocationModel();
            }
        } else {
            goodsFramgentModel.sendLocation.get().setProvinceName("新疆");
            goodsFramgentModel.sendLocation.get().setCityName("乌鲁木齐");
            goodsFramgentModel.sendLocation.get().setAreaName("天山区");
            goodsFramgentModel.getLocationModel();
        }
    }



    //认证dialog
    private void showDialogAuth(String type) {
        View view = View.inflate(getActivity(), R.layout.dialog_two_btn, null);
        final RoundCornerDialog roundCornerDialog = new RoundCornerDialog(getActivity(), 0, 0, view, R.style.RoundCornerDialog);
        roundCornerDialog.show();
        roundCornerDialog.setCanceledOnTouchOutside(false);// 设置点击屏幕Dialog不消失

        TextView tv_message = (TextView) view.findViewById(R.id.tv_message);
        TextView tv_title = view.findViewById(R.id.tv_title);
        TextView tv_logout_confirm = (TextView) view.findViewById(R.id.tv_logout_confirm);
        tv_title.setVisibility(View.VISIBLE);
        TextView tv_logout_cancel = (TextView) view.findViewById(R.id.tv_logout_cancel);

        if (type.equals("manager")) {
            tv_title.setText("认证");
            tv_message.setText("请先进行企业认证再操作");
        } else if (type.equals("driver")) {
            tv_title.setText("认证");
            tv_message.setText("请先进行司机认证再操作");
        } else if (type.equals("nocar")) {
            tv_title.setText("无可用车辆");
            tv_message.setText("请先添加车辆");
            tv_logout_confirm.setText("去添加");
        } else if (type.equals("driverFail")) {
            tv_title.setText("司机认证不通过");
            tv_message.setText("请重新提交认证信息");
        } else if (type.equals("managerFail")) {
            tv_title.setText("企业认证不通过");
            tv_message.setText("请重新提交认证信息");
        } else if (type.equals("driverStandby")) {
            tv_title.setText("司机认证审核中");
            tv_message.setText("认证通过后才能操作");
        } else if (type.equals("managerStandby")) {
            tv_title.setText("企业认证审核中");
            tv_message.setText("认证通过后才能操作");
        }

        //确定
        tv_logout_confirm.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (type.equals("manager") || type.equals("managerFail")) {
                    AuthActivity3.start(getActivity());
                } else if (type.equals("driver") || type.equals("driverFail")) {
                    //                  AddVehicleActivity.start(getActivity());
                    Intent intent = new Intent(getActivity(), AddDriverInfoActivity.class);
                    startActivity(intent);
                } else if (type.equals("nocar")) {
                    AddCarActivity.start(getActivity());
                }
                roundCornerDialog.dismiss();
            }
        });

        //取消
        tv_logout_cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                roundCornerDialog.dismiss();
            }
        });
    }

    public void showCarInfo(List<CarInfo> carInfo) {
        this.carInfo = carInfo;

       /* if (mapGoodsPopWindow != null) {
            mapGoodsPopWindow.setCarInfo(carInfo);

        }*/
    }

    @Override
    public void onCameraChange(CameraPosition cameraPosition) {

    }

    @Override
    public void onCameraChangeFinish(CameraPosition position) {

        currentLatLng = position.target;
        //图标点击时不做请求
        if (isMapClick) {
            return;
        }
        getCurrentRaduis();
        if (isLoadType) {
            isLoadType = false;
            goodsFramgentModel.getGoodsType();
        }
    }

    //获取当前缩放比例下的地图半径
    public void getCurrentRaduis() {
        if (mScreenHeight == 0) {
            mScreenHeight = ScreenUtil.getDisplayHeight();
        }
        //屏幕高度的一半 * 当前缩放1px代表的米数
        goodsFramgentModel.raduis = NumberUtil.trim0(mScreenHeight / 2f * aMap.getScalePerPixel());
        MLog.d("地图半径:", goodsFramgentModel.raduis + "");
    }


    public void cityByLoction(double lat, double lon) {
        //通过经纬度获取位置信息
        GeocodeSearch geocodeSearch = new GeocodeSearch(getActivity());
        // 第一个参数表示一个LatLng，第二参数表示范围多少米，第三个参数表示是火系坐标系还是GPS原生坐标系
        RegeocodeQuery query = new RegeocodeQuery(new LatLonPoint(lat,
                lon), 200, GeocodeSearch.AMAP);
        geocodeSearch.getFromLocationAsyn(query);
        //搜索位置信息
        geocodeSearch.setOnGeocodeSearchListener(new GeocodeSearch.OnGeocodeSearchListener() {
            @Override
            public void onRegeocodeSearched(RegeocodeResult result, int code) {
                if (code != 1000) return;
                RegeocodeAddress address = result.getRegeocodeAddress();
                if (address != null) {

                    refreshSendCitySelect(address.getProvince(), address.getCity(), address.getDistrict());


                }
            }

            @Override
            public void onGeocodeSearched(GeocodeResult result, int code) {

            }
        });
    }

    //地图移动时刷新发货地文字
    private void refreshSendCitySelect(String province, String city, String district) {
        sendGoodsLocationPopWindow3.setDataAndPosition(addressEntityList, province,city,district,true,false);
        BaseAreaEntity[] entities= sendGoodsLocationPopWindow3.findCode(province,city,district);
        binding.tvSend.setText(entities[1].getSimpleName());
    }
    public boolean isContainCarTypeAndCarLengthByGoodsNo(String goodsNo) {
        if (goodsNo == null) {
            return false;
        }
        return allCarTypeAndCarLengthMap.keySet().contains(goodsNo);
    }
    public void setCarTypeAndCarLength(String goodsTypeNo, List<CarTypeAndCarLength> list) {
        if (!isContainCarTypeAndCarLengthByGoodsNo(goodsTypeNo)) {
            allCarTypeAndCarLengthMap.put(goodsTypeNo, list);
        }
        showMoreFilterPopWindow(list);
    }
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void getCode(MessageEvent event) {
        switch (event.code) {
            case EventConstant
                    .EVENT_REFRESH:
                UserOperating.getInstance().refresh();
                break;
        }
    }
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvent(LogisticsEvent event) {
       if (event.getMessageTag() == EventConstant.EVENT_CARINFO_COMMIT) {//接收新增车辆提交事件
           UserOperating.getInstance().refresh();
        }
    }
    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }
}
